package com.school.service.impl;

import com.school.entity.SelfStatementReport;
import com.school.repository.SelfStatementReportRepository;
import com.school.service.SelfStatementReportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class SelfStatementReportServiceImp implements SelfStatementReportService {
    @Autowired
    SelfStatementReportRepository selfStatementReportRepository;

    /**
     * 增加
     * @param selfStatementReport
     * @return
     */
    @Override
    public SelfStatementReport addSelfStatementReport(SelfStatementReport selfStatementReport) {
        return selfStatementReportRepository.save(selfStatementReport);
    }

    /**
     * 修改
     * @param selfStatementReport
     * @return
     */
    @Override
    public SelfStatementReport updateSelfStatementReport(SelfStatementReport selfStatementReport) {
        return selfStatementReportRepository.saveAndFlush(selfStatementReport);
    }

    /**
     * 根据条件分页查询
     * @param selfStatementReport,page,size
     */
    @Override
    public Page<SelfStatementReport> specificPageQuerySelfStatementReportList(SelfStatementReport selfStatementReport, int page, int size) {
        Specification querySpecification = new Specification() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if(selfStatementReport != null)
                {
                    String studentId = selfStatementReport.getStudentId();
                    if (!StringUtils.isEmpty(studentId)) {
                        predicates.add(criteriaBuilder.equal(root.get("studentId").as(String.class), studentId));
                    }
                }
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        PageRequest pageRequest = PageRequest.of(page-1, size, Sort.by(Sort.Direction.DESC,"updateDate"));
        return selfStatementReportRepository.findAll(querySpecification,pageRequest);
    }
}
